package com.alibaba.citrus.cr.platform.enhance.repository.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.citrus.cr.common.util.TimeUtil;
import com.alibaba.citrus.cr.platform.enhance.repository.ScItemRepository;
import com.alibaba.citrus.cr.platform.enhance.repository.model.DubboResult;
import com.alibaba.citrus.cr.platform.enhance.repository.utils.ResultUtils;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSON;

import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crplatformenhance.domain.scitemgroup.service.ScItemGroupService;
import com.epoch.app.crplatformenhance.dto.request.QueryScItemRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemSDO;
import com.epoch.app.crplatformenhance.model.enums.ScItemMarkTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

/**
 * @author zls
 * @description: TODO
 * @date 2021/9/7 18:08
 */
@Component
public class ScItemRepositoryImpl implements ScItemRepository {
    @Resource
    ScItemGroupService scItemGroupService;
    @Resource
    BaseDataService baseDataService;

    @Override
    public Boolean createScItem(ScItemSDO scItemSDO) {

        BaselineCreateScItemRequest createRequest = createRequestConverter(scItemSDO);
        DubboResult result = ResultUtils.getDubboResult((Map) baseDataService.baselineCreateScItem(createRequest));
        return result.getSuccess();
    }

    private BaselineCreateScItemRequest createRequestConverter(ScItemSDO scItemSDO) {
        BaselineCreateScItemRequest baselineCreateScItemRequest = new BaselineCreateScItemRequest();
        BeanUtils.copyProperties(scItemSDO, baselineCreateScItemRequest);
        baselineCreateScItemRequest.setScItemPublishDTO(scItemSDO);
        return baselineCreateScItemRequest;
    }


    @Override
    public Boolean editScItem(ScItemSDO scItemSDO) {
        BaselineEditScItemRequest editRequest = updateRequestConverter(scItemSDO);
        DubboResult result = ResultUtils.getDubboResult((Map) baseDataService.baselineEditScItem(editRequest));
        return result.getSuccess();
    }

    private BaselineEditScItemRequest updateRequestConverter(ScItemSDO scItemSDO) {
        BaselineEditScItemRequest baselineCreateScItemRequest = new BaselineEditScItemRequest();
        BeanUtils.copyProperties(scItemSDO, baselineCreateScItemRequest);
        baselineCreateScItemRequest.setScItemEditDTO(scItemSDO);
        return baselineCreateScItemRequest;
    }

    @Override
    public ScItemSDO getScItem(String itemId) {
        BaselineQueryScItemIdRequest request = BaselineQueryScItemIdRequest.builder()
                .id(itemId)
                .build();
        DubboResult result = ResultUtils.getDubboResult((Map) baseDataService.baselineQueryScItemId(request));
        if (!result.getSuccess() || result.getResult() == null) {
            return null;
        }
        Map map = (Map) result.getResult();
        Object scItemObject = map.get("scItemSDO");
        if (scItemObject == null) {
            return null;
        }
        ScItemSDO scItemSDO = JSON.parseObject(JSON.toJSONString(scItemObject), ScItemSDO.class);
        return scItemSDO;
    }

    @Override
    public PageResult<List<ScItemSDO>> pageQueryScItemList(QueryScItemRequest request) {
        if (request == null) {
            request = new QueryScItemRequest();
        }
        //默认查询常温货品
        if(StringUtils.isBlank(request.getBusinessType())){
            request.setBusinessType("11");
        }
        //默认查询非组合货品
        if(Objects.isNull(request.getType())){
            request.setType(0);
        }
        BaselineQueryScItemByPageRequest queryRequest = loadListRequestConverter(request);
        Object o = baseDataService.baselineQueryScItemByPage(queryRequest);
        DubboResult result = ResultUtils.getDubboPageResult((Map) o);
        List<Map<String, Object>> list = (List<Map<String, Object>>) result.getResult();
        List<ScItemSDO> data = list.stream().map(bean -> {
            return scItemConverter(bean);

        }).collect(Collectors.toList());
        return PageResult.of(data, result.getTotal());

    }

    @Override
    public PageResult<List<ScItemSDO>> pageQueryScItemListFromDB(QueryScItemRequest request) {
        if (request == null) {
            request = new QueryScItemRequest();
        }
        //默认查询常温货品
        if(StringUtils.isBlank(request.getBusinessType())){
            request.setBusinessType("11");
        }
        //默认查询非组合货品
        if(Objects.isNull(request.getType())){
            request.setType(0);
        }
        BaselineQueryScItemByPageFromDbRequest queryRequest = loadListDbRequestConverter(request);
        Object o = baseDataService.baselineQueryScItemByPageFromDb(queryRequest);
        DubboResult result = ResultUtils.getDubboPageResult((Map) o);
        List<Map<String, Object>> list = (List<Map<String, Object>>) result.getResult();
        List<ScItemSDO> data = list.stream().map(bean -> scItemConverter(bean)).collect(Collectors.toList());
        return PageResult.of(data, result.getTotal());

    }

    private ScItemSDO scItemConverter(Map map) {
        ScItemSDO scItemSDO = new ScItemSDO();
        scItemSDO.setBarCode(Objects.isNull(map.get("barCode")) ? "" : map.get("barCode").toString());
        // 这里需要查询品牌
        scItemSDO.setBrandId(Objects.isNull(map.get("brandId")) ? "" : map.get("brandId").toString());
        scItemSDO.setScItemId(map.get("scItemId").toString());
        scItemSDO.setLeafCategoryId(Objects.isNull(map.get("leafCategoryId")) ? "" : map.get("leafCategoryId").toString());
        //  实际蒙牛货品的很多字段都在features中
        scItemSDO.setFeatures((Map) map.get("features"));
        scItemSDO.setOuterId(Objects.isNull(map.get("outerId")) ? "" : map.get("outerId").toString());
        scItemSDO.setTitle(map.get("title").toString());
        scItemSDO.setType(Integer.getInteger(map.get("type").toString()));
        scItemSDO.setUnit(Objects.isNull(map.get("unit")) ? "" : map.get("unit").toString());
        scItemSDO.setStatus(Objects.isNull(map.get("status")) ? -1 : Double.valueOf(map.get("status").toString()).intValue());
        if (Objects.nonNull(map.get("gmtModified"))) {
            String gmtModifiedStr = map.get("gmtModified").toString();
            Date gmtModified = TimeUtil.parseTime(gmtModifiedStr);
            scItemSDO.setGmtModified(gmtModified);
        }
        if (Objects.nonNull(map.get("gmtCreate"))) {
            String gmtCreateStr = map.get("gmtCreate").toString();
            Date gmtCreate = TimeUtil.parseTime(gmtCreateStr);
            scItemSDO.setGmtCreate(gmtCreate);
        }
        return scItemSDO;
    }

    private BaselineQueryScItemByPageRequest loadListRequestConverter(QueryScItemRequest request) {
        BaselineQueryScItemByPageRequest queryScItemByPageRequest = BaselineQueryScItemByPageRequest.builder()
                .start(request.getStart())
                .limit(request.getLimit())
                .page(request.getStart() / request.getLimit() + 1)
                .idList(request.getScItemIdList())
                .title(request.getTitle())
                .outId(request.getOuterId())
                .brandId(request.getBrandId())
                .categoryId(request.getCategoryId())
                .businessType(request.getBusinessType())
                .type(request.getType())
                .statusList(request.getStatusList())
                .build();
        return queryScItemByPageRequest;
    }

    private BaselineQueryScItemByPageFromDbRequest loadListDbRequestConverter(QueryScItemRequest request) {
        BaselineQueryScItemByPageFromDbRequest queryScItemByPageRequest = BaselineQueryScItemByPageFromDbRequest.builder()
                .start(request.getStart())
                .limit(request.getLimit())
                .page(request.getStart() / request.getLimit() + 1)
                .idList(request.getScItemIdList())
                .title(request.getTitle())
                .outId(request.getOuterId())
                .brandId(request.getBrandId())
                .categoryId(request.getCategoryId())
                .businessType(request.getBusinessType())
                .type(request.getType())
                .statusList(request.getStatusList())
                .build();
        if (null != request.getScMarkType()) {
            Boolean scMarkType = request.getScMarkType();
            FeatureSearchReqDTO featureSearchReqDTO =new FeatureSearchReqDTO();
            featureSearchReqDTO.setKey(ScItemMarkTypeEnum.NEW_SC_ITEM.getFiled());
            featureSearchReqDTO.setValue(ScItemMarkTypeEnum.NEW_SC_ITEM.getMarkType());
            if (scMarkType) {
                queryScItemByPageRequest.setFeaturesSearchList(Collections.singletonList(featureSearchReqDTO));
            }else {
                queryScItemByPageRequest.setFeaturesSearchNotList(Collections.singletonList(featureSearchReqDTO));
            }
        }
        return queryScItemByPageRequest;
    }
}
